#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]){
    int sockfd, n;
    struct sockaddr_in servaddr;
    char *ip = "127.0.0.1";
    char buff[1024];
    char *ptr = buff;
    char fchar,schar;
    char finish = 0;

    if((sockfd = socket(AF_INET,SOCK_STREAM, 0)) < 0) {
        perror("socket");
        return -1;
    }

    memset(&servaddr, 0 ,sizeof(struct sockaddr_in));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(9111);
    inet_pton(AF_INET, ip, &servaddr.sin_addr);

    if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("connect");
        return -1;
    }
    printf("连接成功\n");
    for(;;) {
        int nleft = 1023;
        char flag = 0;
        ptr = buff;
        while(nleft > 0) {
            if((n = read(sockfd, &schar, 1)) < 0 ) {
                if (errno == EINTR) {
                    n = 0;
                } else {
                    perror("socket read");
                    return -1;
                }
            } else if(n == 0 ) {
                *ptr = 0;
                finish = 1;
                break;   
            } else {
                *ptr++ = schar;
                if(flag == 0) {
                    fchar = schar;
                    flag = 1;
                }else if ( schar == '\n' && fchar == '\r') {
                    break;
                }else {
                    fchar = schar;
                }
            }
            nleft -= n;
        }
        *ptr = 0;
        printf("time: %s\n",buff);
        if(finish == 1) break;
    }
    return 0;
}